import os
import re
import linecache
import sys

# 遍历模块中可以被引用 .h 文件
allPodFile = {}
# 本地模块和其路径的map
localmodules = {}
allpath = []
allname = []



def getLocalPods(): 
    """ 1 通过Podfile.local 遍历本地组件
          localmodules 存储本地模块和其路径的map
    """
    headerText = ''
    with open("Podfile.lock", "r",  encoding="gb18030", errors='ignore') as Pod:
        for line in Pod :
            #读取本地路径
            if ":path:" in line:
                module = headerText.strip().strip(":")
                path = eval(line.split()[-1])
                localmodules[module] = path
                # 注意 ../Scene/TuyaSmartSceneKit/TuyaSmartSceneKit 
                getAllPodsFile(os.path.join(path+"/"+module), module)
            #获取:path: 前一行
            else:
                headerText = line


def getPodsModule(path):
    """ 2. 遍历 Pods 中所有模块
           然后去遍历模块中可被引用文件
    """
    allfilelist = os.listdir(path)
    for fileName in allfilelist:
        if fileName == "Headers":
            continue
        filePath = os.path.join(path, fileName)
        # 如果是文件夹(获取所有模块)
        if os.path.isdir(filePath):
            getAllPodsFile(filePath, fileName)


def getAllPodsFile(path, module):
    """ 
     3. 遍历模块中可被引用的 .h 文件
    :param path:文件路径
    :param module:模块名称
    """
    try:
       allfilelist = os.listdir(path)
    except :
        print ("找不到这个路径", path)
    else: 
        for fileName in allfilelist:
            filePath = os.path.join(path, fileName)
            # 如果是文件夹，递归调用函数
            if os.path.isdir(filePath):
                getAllPodsFile(filePath, module)
            # 如果不是文件夹，保存文件路径及文件名
            elif os.path.isfile(filePath) and fileName.endswith('.h'):
                allPodFile[fileName] = module


# 获取所有的.h 和 .m  .mm 文件
def getallfile(path):

    allfilelist = os.listdir(path)
    # 遍历该文件夹下的所有目录或者文件
    for fileName in allfilelist:
        if fileName.endswith('.framework'):
            continue
        filePath = os.path.join(path, fileName)
        # 如果是文件夹，递归调用函数
        if os.path.isdir(filePath):
            getallfile(filePath)
        # 如果不是文件夹，保存文件路径及文件名
        elif os.path.isfile(filePath):
            if fileName.endswith('.h') or fileName.endswith('.m') or fileName.endswith('.mm') or fileName.endswith('.pch'):
                allpath.append(filePath)
                allname.append(fileName)
    return allpath, allname


def findImport(path):
    # 5 遍历 import 错误文件
    getallfile(path)
    for file in allpath:
        with open(file, "r", encoding="gb18030", errors='ignore') as f:
            # 分行读取内容
            for line in f:
                text = line.strip()
                # 获取 import
                if text.startswith('#import'):
                    if text.endswith('.h"'):
                        for header in re.split('\"|\/', text):
                            if header not in allname and header.endswith('.h'):
                                if header in allPodFile.keys():
                                    newHeader = "#import <%s/%s>" % (
                                        allPodFile[header], header)
                                    updateFile(file, text, newHeader)
                                    print("我们将", os.path.basename(
                                        file), "文件中的", text, "改为", newHeader)

                    if text.endswith('.h>') and "/" not in text:
                        for header in re.split('\<|\>', text):
                                # print(text, header)
                                if header in allPodFile.keys():
                                    newHeader = "#import <%s/%s>" % (
                                        allPodFile[header], header)
                                    updateFile(file, text, newHeader)
                                    print("我们将", os.path.basename(
                                        file), "文件中的", text, "改为", newHeader)


def updateFile(file, old_str, new_str):
    """
    6. 替换文件中的字符串
    :param file:文件名
    :param old_str:就字符串
    :param new_str:新字符串
    :return:
    """
    file_data = ""
    with open(file, "r", encoding="gb18030", errors='ignore') as f:
        for line in f:
            if old_str in line:
                line = line.replace(old_str, new_str)
            file_data += line
    with open(file, "w", encoding="gb18030", errors='ignore') as f:
        f.write(file_data)


if __name__ == '__main__':
    
    getLocalPods()
    getPodsModule(os.path.join("Pods"))
    #4. 输入组件名称 查看是否在本地
    name = input("请输入组件名称: ")
    if name in  localmodules:
    #    findImport(os.path.join(localpath))
        findImport(os.path.join(localmodules[name]+"/"+name))
    else:
        print (name, "组件不在本地,请检查Podfile,执行pod install")
